package cn.icare.cms.controller;

import cn.icare.cms.*;
import cn.icare.cms.config.WxInfoConfig;
import cn.icare.cms.dao.po.Member;
import cn.icare.cms.dao.po.MemberCoupon;
import cn.icare.cms.model.enums.CommonStatusEnum;
import cn.icare.cms.model.enums.UserTypeEnum;
import cn.icare.cms.model.ro.WxMemberLoginRo;
import cn.icare.cms.model.vo.rest.RespMsgVO;
import cn.icare.cms.model.vo.rest.UserLoginRespVO;
import cn.icare.cms.model.wx.ro.GetSessionRo;
import cn.icare.cms.model.wx.ro.WxConfig;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

@CrossOrigin
@RestController
@RequestMapping(value = "/rest/member")
@Api(tags = "REST会员")
public class MemberController extends BaseController {
    @Autowired
    private MemberService memberService;
    private final String FALL_STRING = "请求失败,服务繁忙!";


    @Value("${cms.tokenTime}")
    private Long tokenTime; //单位小时


    @Value("${cms.refreshTokenTime}")
    private Long refreshTokenTime; //单位小时

    @Autowired
    private WxService wxService;

    @Autowired
    private WxInfoConfig wxInfoConfig;

    @Autowired
    private CouponService couponService;

    @Autowired
    private MemberCouponService memberCouponService;


    /**
     * 会员登录-微信方式
     *
     * @return
     */
    @PostMapping("/wxlogin")

    @ApiOperation(value = "会员注册及登录接口-微信方式", notes = "会员注册及登录接口-微信方式")
    public ResponseEntity<RespMsgVO> wxLogin(@RequestBody WxMemberLoginRo ro) {

        //通过微信接口解密手机号码
        String realPhoneNumber = ""; //明文手机号码
        //TODO 测试代码，先用传入的手机号码赋值给realPhoneNumber
        GetSessionRo sessionRo = new GetSessionRo();
        sessionRo.setJs_code(ro.getCode());
        WxConfig wxConfig = JSON.parseObject(JSONObject.toJSONString(wxInfoConfig), WxConfig.class);
        String decodeData = wxService.getWXDecodeDate(wxConfig, sessionRo, ro.getPhoneNumber(), ro.getIv());
        //解密出来的数据格式如：{"phoneNumber":"15990146207","purePhoneNumber":"15990146207","countryCode":"86","watermark":{"timestamp":1584162989,"appid":"wx496a5cc132468b14"}}
        if (StringUtil.isNotEmpty(decodeData)) {
            JSONObject object = JSONObject.parseObject(decodeData);
            realPhoneNumber = object.getString("purePhoneNumber");//获取手机号码，不带国外的区别
        }
        if (StringUtil.isEmpty(realPhoneNumber)) {
            return super.getRespFail("手机号码解码失败");
        }

        //通过手机号查询会员是否已经注册
        Member member = memberService.getOneByPhone(realPhoneNumber);
        if (member == null) {
            //如果未注册，自动注册
            member = new Member();
            member.setUsername("gb_" + realPhoneNumber);
            member.setPhone(realPhoneNumber);
            member.setName(ro.getNickname());
            member.setPhoto(ro.getAvatarUrl());
            member.setStatus(CommonStatusEnum.EABLED.getCode());
            member.setCreatetime(new Date());
            member.setUpdatetime(member.getCreatetime());
            member.setWxcode(ro.getCode());
            Long id = memberService.createOne(member);
            if (id > 0) {
                member.setId(id);
                //领取新人优惠券
                this.getNewMeberCounon(id);

            }
        }
        if (member.getId() > 0) {
            JwtUtil jwtUtil = new JwtUtil();
            Integer type = UserTypeEnum.Member.getCode(); //用户类型
            //创建token
            String token = jwtUtil.createJWT(member.getId(), tokenTime * 60 * 60 * 1000, type);
            //创建refreshToken
            String refreshToken = jwtUtil.createJWT(member.getId(), refreshTokenTime * 60 * 60 * 1000, type);
            Map<String, Object> result = new HashMap<>();
            result.put("member", member);
            result.put("token", token);
            result.put("refreshToken", refreshToken);
            return super.getRespOk(result);
        } else {
            return super.getRespFail("服务繁忙，请稍候再试");
        }


        //   return this.client.getAllAD();
    }



    /**
     * URL:http://{ip}:{port}/rest/user/login
     * method:POST
     *
     * @return
     */
    @PostMapping("/refreshToken")
    @ApiOperation(value = "自动刷新用户登录状态", notes = "自动刷新用户登录状态")
    public ResponseEntity<RespMsgVO> refreshToken(HttpServletRequest request) {
        Member member=this.getCurrentUser(request);
        if (member!=null && member.getId() > 0) {
            JwtUtil jwtUtil = new JwtUtil();
            Integer type = UserTypeEnum.Member.getCode(); //用户类型
            //创建token
            String token = jwtUtil.createJWT(member.getId(), tokenTime * 60 * 60 * 1000, type);
            //创建refreshToken
            String refreshToken = jwtUtil.createJWT(member.getId(), refreshTokenTime * 60 * 60 * 1000, type);
            Map<String, Object> result = new HashMap<>();
            result.put("member", member);
            result.put("token", token);
            result.put("refreshToken", refreshToken);
            return super.getRespOk(result);
        }
        else
        {

            return super.getRespUNAUTHORIZED("刷新用户登录状态失败，请重新登录");
        }
    }



    /**
     * 数据解码测试接口
     *
     * @return
     */
    @PostMapping("/decodetest")

    @ApiOperation(value = "数据解码测试接口", notes = "数据解码测试接口")
    public ResponseEntity<RespMsgVO> wxLogin() {


//        String sessionKey = "wS8Bn0quxgifVSR59myF2w==";
//        String encryptedData = "lWEAjOlJc9vD0knWbAuK0ZKROuEu6KoO+PquKVJ3dYl1M1VPrgNO3hnCBHamVzS3nFFG+guNN+yOt+sHPYKKCJ3ddODgHUIQ5P29aiKeW7PI/VOVSwYZXepQGP6OE8iB0g+3o/1LERPTNqRsq7P2oKD34aBASLBP1vjXUZKvYwGoi+O5Jj4nCuzWMxQEU6z5OlWOkd4R5e3lBx9Zc8Y6qA==";
//
//        String iv = "cpRpQ7PExjB42p1XHOEaXg==";
//
//        RespMsgVO result = wxService.getASEDecodeData(sessionKey, encryptedData, iv);
//        if (result.getCode() == 0) {
//            return super.getRespOk(result.getResData().toString());
//        } else
//            return super.getRespFail("code:" + result.getCode() + " " + result.getMsg());
//
        getNewMeberCounon(1L);

        return   super.getRespOk();

    }

    //#region fallback methods
    private ResponseEntity<RespMsgVO> getAllFall() {
        return super.getRespFail("查询区域失败，服务繁忙，请稍候再试");
    }


    public static void main(String[] args) {
//        String msg= "{\"session_key\":\"HFad+gidaN5lnQRdzaFZzw==\",\"openid\":\"ohLSX5Pk0kWqKW9eRQaMeqon1KjE\"}";
//        JSONObject jsonObject = JSONObject.parseObject(msg);
//        WxUserInfoVo vo = JSON.parseObject(jsonObject.toJSONString(), WxUserInfoVo.class);
//        String sessionKey="wS8Bn0quxgifVSR59myF2w==";
 //       String encryptedData="lWEAjOlJc9vD0knWbAuK0ZKROuEu6KoO+PquKVJ3dYl1M1VPrgNO3hnCBHamVzS3nFFG+guNN+yOt+sHPYKKCJ3ddODgHUIQ5P29aiKeW7PI/VOVSwYZXepQGP6OE8iB0g+3o/1LERPTNqRsq7P2oKD34aBASLBP1vjXUZKvYwGoi+O5Jj4nCuzWMxQEU6z5OlWOkd4R5e3lBx9Zc8Y6qA==";
        JwtUtil jwtUtil = new JwtUtil();
        String token = jwtUtil.createJWT(19L, 7 * 60 * 60 * 1000, 2);
        System.out.println("token:" + token);


    }
    //#endregion

    private void getNewMeberCounon(Long memberId)
    {
       List<Map<String,Object>> coupons= this.couponService.getOnlyNewMemberList();
       if(coupons!=null && coupons.size()>0) {

           coupons.parallelStream().forEach(item->{
               Integer couponId=Integer.valueOf(item.get("id").toString());
               MemberCoupon addMemberCouponRO= new MemberCoupon();
               addMemberCouponRO.setCouponid(couponId);
               addMemberCouponRO.setMemberid(memberId);
               addMemberCouponRO.setStarttime(DateUtil.toDate(item.get("starttime").toString(),"yyyy-MM-dd HH:mm:ss"));
               addMemberCouponRO.setEndtime(DateUtil.toDate(item.get("endtime").toString(),"yyyy-MM-dd HH:mm:ss"));
               Integer result = this.memberCouponService.createOne(addMemberCouponRO);
               if (result > 0) {
                   //更新优惠券已领用数量
                   Integer getTotal = Integer.valueOf(item.get("gettotal").toString());
                   getTotal = getTotal + 1;
                   boolean sucess = this.couponService.updateOneGetTotal(couponId, getTotal);
               }
           });

       }

    }}
